<template>
	<el-card>
		<el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList()">
			<el-form-item>
				<el-input v-model="state.queryForm.userId" placeholder="用户ID"></el-input>
			</el-form-item>
			<el-form-item>
				<el-input v-model="state.queryForm.owner" placeholder="存证者"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button @click="getDataList()">查询</el-button>
			</el-form-item>
			<el-form-item v-auth="'sys:attachment:save'">
				<template #default="scope">
					<!-- <el-button type="primary" @click="issue(scope.row)">手动信息存证</el-button> -->
					<!-- Form  这部分会变形-->
					<el-dialog v-model="dialogFormVisibleIssue" title="请输入存证内容" :modal="false" clearable="true">
						<generate-form ref="issueFormRef" :data="widgetFormIssue"></generate-form>
						<el-upload ref="uploadRef" class="upload-demo" :http-request="uploadFiles" :auto-upload="false" :on-success="handleSuccess" multiple>
							<template #trigger>
								<el-button type="primary" class="mr-10">点击选择</el-button>
							</template>

							<template #tip>
								<div class="el-upload__tip">图片格式为jpg/png，图片大小不得超过5MB</div>
							</template>
							<!-- 使用栅格布局 -->
							<div class="el-row">
								<div class="el-col el-col-offset-md-2 el-col-md-20">
									<!-- 根据需要调整 el-col-{ breakpoint }-{ width } 的值 -->
								</div>
							</div>
						</el-upload>
						<template #footer>
							<span class="dialog-footer">
								<el-button @click="dialogFormVisibleIssue = false">取消</el-button>
								<el-button type="primary" @click="handleSubmitIssueForm()"> 提交</el-button>
							</span>
						</template>
					</el-dialog>
				</template>
			</el-form-item>
			<el-form-item>
				<el-button v-auth="'sys:attachment:delete'" type="danger" @click="deleteList()">批量删除</el-button>
			</el-form-item>
		</el-form>
		<el-table :data="state.dataList" border style="width: 100%" @selection-change="selectionChangeHandle">
			<el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
			<el-table-column label="序号" header-align="center" align="center">
				<template #default="scope">
					{{ scope.row.index + 1 }}
				</template>
			</el-table-column>
			<el-table-column prop="userId" label="用户ID" show-overflow-tooltip header-align="center" align="center"></el-table-column>
			<el-table-column prop="deviceId" label="设备ID" show-overflow-tooltip header-align="center" align="center"></el-table-column>
			<el-table-column prop="beforeEncrypt" label="加密前原始数据" show-overflow-tooltip header-align="center" align="center"></el-table-column>
			<el-table-column prop="afterEncrypt" label="加密后数据" show-overflow-tooltip header-align="center" align="center"></el-table-column>
			<el-table-column prop="syncCount" label="溯源数据量" header-align="center" align="center"></el-table-column>
			<el-table-column label="加密证书" header-align="center" align="center">
				<template #default="scope">
					<el-button type="primary" link @click="downloadCertificateHandle(scope.row.downloadPath, scope.row.sysObjectName)"> 下载证书</el-button>
				</template>
			</el-table-column>
			<el-table-column show-overflow-tooltip  prop="createTime" label="创建时间" header-align="center" align="center"></el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="200">
				<template #default="scope">
					<!-- Form -->
					<!-- <el-button type="primary" link @click="edit(scope.row)">编辑</el-button> -->
					<el-dialog v-model="dialogFormVisible" title="请输入编辑内容" :modal="false">
						<generate-form ref="generateFormRef" :data="widgetForm"></generate-form>
						<template #footer>
							<span class="dialog-footer">
								<el-button @click="dialogFormVisible = false">取消</el-button>
								<el-button type="primary" @click="handleSubmit(scope.row)"> 提交</el-button>
							</span>
						</template>
					</el-dialog>

					<el-button v-auth="'sys:attachment:delete'" type="primary" link @click="deleteList(scope.row.id)"> 删除 </el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.page"
			:page-sizes="state.pageSizes"
			:page-size="state.limit"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
		>
		</el-pagination>
	</el-card>
</template>

<script setup lang="ts" name="SysAttachmentIndex">
import { useCrud } from '@/hooks/fabricIndex'
import { reactive, ref } from 'vue'
import { IHooksOptions } from '@/hooks/interface'
import { ElMessage, ElMessageBox, UploadInstance } from 'element-plus'
import type { UploadProps } from 'element-plus'
import { useAttachmentSubmitApi } from '@/api/sys/attachment'
import service from '@/utils/request'

const state: IHooksOptions = reactive({
	dataListUrl: '/traceabilityData/queryPage',
	deleteUrl: '/traceabilityData/listDelete',
	queryForm: {
		id: '',
		deviceId: '',
		userId: '',
		beforeEncrypt: '',
		afterEncrypt: '',
		syncCount: ''
	}
})
const dataForm = reactive({
		id: '',
		deviceId: '',
		userId: '',
		beforeEncrypt: '',
		afterEncrypt: '',
		syncCount: '',
		downloadPath:''
})
const url = import.meta.env.VITE_API_URL
const uploadFiles = async file => {
	const formData = new FormData()
	formData.append('file', file.file)
	formData.append('dir', file.getFileName)
	//const url = import.meta.env.VITE_API_URL + `sys/object/upload? dir=${file.getFileName} && accessToken=` + cache.getToken()
	const url = import.meta.env.VITE_API_URL + 'sys/object/upload'
	await service.post(url, formData).then(res => {
		size.value = res.data.fileSize
		console.log('打印res ', JSON.stringify(res))
	})
}
//上传图片
const uploadRef = ref<UploadInstance>()

const submitUpload = () => {
	uploadRef.value!.submit()
}
//图片返回参数结构体
const fileStructure = reactive({
	filePath: '',
	fileName: '',
	fileSize: 0,
	fileContentType: ''
})

//临时使用的尺寸
const size = ref(0)
const handleSuccess: UploadProps['onSuccess'] = (res, file) => {
	fileStructure.fileName = res.data.fileName
	fileStructure.filePath = res.data.filePath
	fileStructure.fileContentType = res.data.fileContentType
	fileStructure.fileSize = res.data.fileSize
	if (res.code !== 0) {
		ElMessage.error('上传失败：' + res.msg)
		return false
	}

	Object.assign(dataForm, res.data)

	//上传
	//重构
	const upload = {
		sysObjectPath: fileStructure.filePath,
		sysObjectName: fileStructure.fileName,
		sysObjectSize: fileStructure.fileSize
	}
	useAttachmentSubmitApi(upload).then(res => {
		ElMessage.success({
			message: '上传成功',
			duration: 500,
			onClose: () => {
				getDataList()
			}
		})
	})
}
const { getDataList, selectionChangeHandle, sizeChangeHandle, currentChangeHandle, deleteBatchHandle, downloadCertificateHandle } = useCrud(state)
//存证
const dialogFormVisibleIssue = ref(false)
const issueFormRef = ref()
const widgetFormIssue = {
	list: [
		{
			type: 'grid',
			label: '格栅布局',
			columns: [
				{
					span: 15,
					list: [
						{
							type: 'input',
							label: '存证名字',
							options: {
								defaultValue: '',
								width: '',
								maxlength: 32,
								placeholder: null,
								labelHide: false,
								disabled: false,
								readonly: false,
								clearable: false,
								showPassword: false,
								showWordLimit: false,
								rules: [
									{ required: true, message: '存证名字不为空' },
									{ type: 'string', message: '格式不正确' }
								]
							},
							key: 'insgt0c9',
							name: 'name'
						},
						{
							type: 'input',
							label: '存证者',
							options: {
								defaultValue: '',
								width: '',
								maxlength: 32,
								placeholder: null,
								labelHide: false,
								disabled: false,
								readonly: false,
								clearable: false,
								showPassword: false,
								showWordLimit: false,
								rules: [{ required: true, message: '存证者不为空' }]
							},
							key: 'yawjwkvl',
							name: 'owner'
						},
						{
							type: 'input',
							label: '尺寸',
							options: {
								defaultValue: '',
								width: '',
								maxlength: 32,
								placeholder: null,
								labelHide: false,
								disabled: false,
								readonly: false,
								clearable: false,
								showPassword: false,
								showWordLimit: false,
								rules: [
									{ required: true, message: '尺寸不为空' },
									{ type: 'string', message: '格式不正确' }
								]
							},
							key: 'ihddsdf',
							name: 'appraisedValue'
						},
						{
							type: 'input',
							label: '余量',
							options: {
								defaultValue: '',
								width: '',
								maxlength: 32,
								placeholder: null,
								labelHide: false,
								disabled: false,
								readonly: false,
								clearable: false,
								showPassword: false,
								showWordLimit: false,
								rules: [{ required: true, message: '余量不为空' }]
							},
							key: '1hyol723',
							name: 'collections'
						}
					]
				},
				{ span: 13, list: [] }
			],
			options: { gutter: 0, justify: 'center', align: 'middle' },
			key: 'nrnvtnam',
			name: 'name'
		}
	],
	config: { size: 'default', labelWidth: 100, labelPosition: 'right', style: '' }
}
const issue = (row: any) => {
	dialogFormVisibleIssue.value = true
	console.log(row)
}

const deleteList = (key?: number | string) => {
	let data: any[] = []
	if (key) {
		// data = [{ id: key }]
		data = [key]
	} else {
		data = state.dataListSelections ? state.dataListSelections : []

		if (data.length === 0) {
			ElMessage.warning('请选择删除记录')
			return
		}
	}

	ElMessageBox.confirm('确定进行删除操作?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			if (state.deleteUrl) {
				console.log('打印删除地址{}', state.deleteUrl)
				console.log('打印删除参数', data)
				const transformedData = data.map((id: string) => {
					return { id }
				})
				console.log('转化的数组', transformedData)
				service.post(state.deleteUrl, JSON.stringify(transformedData)).then(() => {
					ElMessage.success('删除成功')
					getDataList()
				})
			}
		})
		.catch(() => {})
}
const handleSubmitIssueForm = async () => {
	await uploadRef.value!.submit()
	console.log()
	await issueFormRef.value
		.getData()
		.then((data: any) => {
			//{"name":"xx","owner":"xx","collections":"xx"}
			// /fabricBasicAsset/save
			console.log('打印data {}', data)
			data.size = size.value
			console.log('打印这次尺寸', size.value)
			console.log('打印结果data', data)
			service.post('/fabricBasicAsset/save', data).then(res => {
				console.log('打印回传信息 ：' + JSON.stringify(res))
			})
			dialogFormVisibleIssue.value = false
			ElMessage.success('存证成功')
			getDataList()
		})
		.catch((error: any) => {
			// data failed
			ElMessage.error('发生未知错误')
		})
}

//编辑
const dialogFormVisible = ref(false)

//编辑表单设计
const generateFormRef = ref()
const edit = (row: any) => {
	dialogFormVisible.value = true
	console.log('编辑的函数' + JSON.stringify(row))
}
let widgetForm = {
	list: [
		{
			type: 'grid',
			label: '格栅布局',
			columns: [
				{
					span: 15,
					list: [
						{
							type: 'input',
							label: '附件标题：',
							options: {
								defaultValue: dataForm.name,
								maxlength: 32,
								placeholder: 'title',
								labelHide: false,
								disabled: false,
								readonly: false,
								clearable: false,
								showPassword: false,
								showWordLimit: false,
								rules: []
							},
							key: 'vk02yvgy',
							name: 'sysObjectName'
						}
					]
				},
				{
					span: 15,
					list: [
						{
							type: 'input',
							label: '附件地址：',
							options: {
								defaultValue: '',
								maxlength: 32,
								placeholder: '/src',
								labelHide: false,
								disabled: false,
								readonly: false,
								clearable: false,
								showPassword: false,
								showWordLimit: false,
								rules: []
							},
							key: 'fw1kssxb',
							name: 'sysObjectPath'
						}
					]
				},
				{
					span: 15,
					list: [
						{
							type: 'input',
							label: '平台地址：',
							options: {
								defaultValue: '',
								maxlength: 32,
								placeholder: 'platform',
								labelHide: false,
								disabled: false,
								readonly: false,
								clearable: false,
								showPassword: false,
								showWordLimit: false,
								rules: []
							},
							key: 'dxdebgb1',
							name: 'sysOrgId'
						}
					]
				}
			],
			options: { gutter: 0, justify: 'center', align: 'top' },
			key: '6ycl80kn',
			name: 'grid_ampkud'
		}
	],
	config: { size: 'default', labelWidth: 100, labelPosition: 'right', style: '' }
}

const handleSubmit = (row: any) => {
	dialogFormVisible.value = false
	generateFormRef.value
		.getData()
		.then((data: any) => {
			//{"title":"xxx","src":"xxx","plat":"xxx"}data...
			///{sys/object}/listUpdate
			data.sysObjectId = row.sysObjectId
			console.log(JSON.stringify(data) + 'data...')
			let array = [data]
			service.post('sys/object/listUpdate', array).then(res => {
				console.log('已经发送数据')
			})
		})
		.catch((error: any) => {
			// data failed
		})
}

//
const value = ref('')
const options = [
	{
		value: 'true',
		label: '是'
	},
	{
		value: 'false',
		label: '否'
	}
]
</script>
<style scoped>
.dialog-footer button:first-child {
	margin-right: 10px;
}
@media screen and (max-width: 100px) {
	.upload-demo {
		margin: 20px auto !important; /* 根据实际情况调整 */
		width: 100%; /* 或者其他合适的宽度 */
	}
}
.upload-demo {
	display: flex;
	justify-content: center;
	align-items: center;
	gap: 10px; /* 为按钮和提示信息之间添加间距 */
}
</style>
